<?php
/**
 * Created by PhpStorm OF yuyi.
 * User: YUYI
 * Date: 2018/5/8 0008
 * Time: 下午 5:30
 * Administrator
 */

namespace app\common\service;


use app\common\model\SysConfig;
use app\common\model\SysConfigUrl;

class SysConfigService extends BaseService
{
    /**
     * 获取系统配置项
     * @param $name string 配置项名称
     * @return string
     */
    public static function getSysConfig($name)
    {
        if (!cache('?sys_config') || !isset(cache('sys_config')[$name])){
            $data = SysConfig::all();
            $result = [];
            foreach ($data as $datum){
                $result[$datum->getData('key')] = $datum->getData('value');
            }
            cache('sys_config',$result);
        }
        $data = cache('sys_config');
        if (!isset($data[$name])){
            return '';
        }
        return $data[$name];
    }

    public static function getAppBaseConfigs()
    {
        if (!cache('?sys_config_app_base')) {
            $sysConfigs = SysConfig::all(function ($query){
                $query->where([['key','like', 'app.base.%']]);
            });
            $result = [];
            foreach ($sysConfigs as $datum) {
                $result[$datum->getData('key')] = $datum->getData('value');
            }
            cache('sys_config_app_base',$result);
            return $result;
        }else{
            return cache('sys_config_app_base');
        }
    }

    public static function delAppBaseConfigs()
    {
        cache('sys_config_app_base',null);
        cache('sys_config',null);
        cache('sys_config_url',null);
    }

    /**
     * 获取URL链接 查询php_config表
     * @param $name
     * @return string
     */
    public static function getURLConfig($name){
        if (!$name){
            return '';
        }
        if (!cache('sys_config_url')||!isset(cache('sys_config_url')[$name])){
            $data = (new SysConfigUrl())->alias('a')
                ->leftJoin('vovoqi.vo_sys_config_url b','a.parentKey = b.key')
                ->field('concat(ifnull(b.value,\'\'),a.value) as value,a.key')
                ->select();
            $result = [];
            foreach ($data as $key => $value){
                $result[$value['key']] = $value['value'];
            }
            cache('sys_config_url',$result);
        }
        $data = cache('sys_config_url');

        if (!isset($data[$name])){
            return '';
        }

        return cache('sys_config_url')[$name];
    }
}